<template>
  <div>
    <div class="warp-box  clearfix">
      <div class="warp-con">
        <div class="search">
          <el-form :inline="true" class="demo-form-inline">
            <el-form-item>
              <el-date-picker
                v-model="selectTime"
                type="datetimerange"
                :picker-options="pickerOptions2"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                align="right">
              </el-date-picker>
              <!--<el-input-->
                <!--v-model="searchFrom.name"-->
                <!--@keyup.enter.native="getBackupList"-->
                <!--auto-complete="off">-->
                <!--<i-->
                  <!--class="el-icon-close el-input__icon"-->
                  <!--slot="suffix"-->
                  <!--@click="searchFrom.name = ''">-->
                <!--</i>-->
              <!--</el-input>-->
            </el-form-item>
            <el-form-item>
              <el-button type="primary"  @click="getBackupList">查询</el-button>
            </el-form-item>
            <el-form-item>
              <el-button type="primary"  @click="addBackupDialog">备份</el-button>
            </el-form-item>
            <!-- <el-form-item>
              <el-button type="primary"  @click="deleteSamplePlot()">批量删除</el-button>
            </el-form-item> -->
          </el-form>
        </div>
        <div class="forms">
          <el-table
            ref="multipleTable"
            border
            stripe
            :data="tableData"
            :tooltip-effect="'dark'"
            style="width: 100%">
            <!--<el-table-column-->
              <!--type="selection">-->
            <!--</el-table-column>-->
            <el-table-column
              prop="backupTime"
              show-overflow-tooltip
              label="备份时间">
            </el-table-column>
            <el-table-column
              prop="fileSize"
              show-overflow-tooltip
              label="文件大小">
            </el-table-column>
            <!--<el-table-column-->
              <!--prop="Sex"-->
              <!--show-overflow-tooltip-->
              <!--label="性别">-->
              <!--<template slot-scope="scope">-->
                <!--{{scope.row.Sex | sexFilter}}-->
              <!--</template>-->
            <!--</el-table-column>-->
            <!--<el-table-column-->
              <!--show-overflow-tooltip-->
              <!--label="创建时间">-->
              <!--<template slot-scope="scope">-->
                <!--{{scope.row.CreateTime | time-formater-has-hour}}-->
              <!--</template>-->
            <!--</el-table-column>-->
            <el-table-column
              label="操作"
              align="center"
              width="140">
              <template slot-scope="scope">
                <el-tooltip class="item" effect="dark" content="下载" placement="top">
                  <el-button @click="download(scope.row)" type="text" title="修改">
                    <span class="pointer">修改</span>
                  </el-button>
                </el-tooltip>
                <!--<el-tooltip class="item" effect="dark" content="删除" placement="top">-->
                  <!--<el-button @click="deleteUser(scope.row)" type="text" title="删除">-->
                    <!--<img src="../../assets/img/home/015.png">-->
                  <!--</el-button>-->
                <!--</el-tooltip>-->
              </template>
            </el-table-column>
          </el-table>
          <el-pagination v-if="tableData && tableData.length && totalNum > 10"
                         @current-change="pager"
                         :current-Page="pageIndex"
                         :page-size="pageSize"
                         layout="total, prev, pager, next, jumper"
                         :total="totalNum">
          </el-pagination>
        </div>
      </div>
    </div>
    <el-dialog :close-on-click-modal="false" :title="detailEditType == 'edit' ? '修改用户信息' : '新增数据备份'" :width="'30%'" top='17%' :show-close="false" :visible.sync="dialogFormVisible">
      <p class="dialogContent" v-show="backuping == false">点击“开始”将开始一个新的数据备份。</p>
      <p class="dialogContent" v-show="backuping == true">正在备份，请稍后...</p>
      <!--<el-form labelPosition='left' class="select-form" :rules="rulesAdd" ref="ruleAddForm" :inline="true" :model="addForm">-->
        <!--<el-form-item class="paddingTB10" label="账户" prop="Account" label-width="140px">-->
          <!--<span v-show="detailEditType == 'edit'">{{addForm.Account}}</span>-->
          <!--<el-input v-show="detailEditType == 'add'" v-model="addForm.Account" auto-complete="off"></el-input>-->
        <!--</el-form-item>-->
        <!--<el-form-item class="paddingTB10" label="真实姓名" prop="UserName" label-width="140px">-->
          <!--<el-input v-model="addForm.UserName" auto-complete="off"></el-input>-->
        <!--</el-form-item>-->
        <!--<el-form-item class="paddingTB10" label="密码" prop="Password" label-width="140px">-->
          <!--<el-input type="password" v-model="addForm.Password" auto-complete="off"></el-input>-->
        <!--</el-form-item>-->
        <!--<el-form-item class="paddingTB10" label="重复输入密码" prop="RePassword" label-width="140px">-->
          <!--<el-input type="password" v-model="addForm.RePassword" auto-complete="off"></el-input>-->
        <!--</el-form-item>-->
        <!--<el-form-item class="paddingTB10" label="性别" prop="Sex" label-width="140px">-->
          <!--<el-select v-model="addForm.Sex" placeholder="请选择">-->
            <!--<el-option-->
              <!--v-for="(item, j) in sexList"-->
              <!--:key="j"-->
              <!--:label="item.label"-->
              <!--:value="item.val">-->
            <!--</el-option>-->
          <!--</el-select>-->
        <!--</el-form-item>-->
      <!--</el-form>-->
      <div slot="footer" class="dialog-footer">
        <el-button v-if="detailEditType == 'edit'" type="primary" @click="updateDetailSubmit('ruleAddForm')">修 改</el-button>
        <el-button v-else type="primary" @click="addBcakup" :disabled='backuping == true'>开 始</el-button>
        <el-button type="primary" @click="dialogFormVisible = false" :disabled='backuping == true'>取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import systemApi from '@/api/systemApi'
export default {
  // name: '订单列表',
  data () {
    var validateAccount = (rule, value, callback) => {
      let uPattern = /^[a-zA-Z0-9]{6,16}$/ // 用户名正则，6到16位（字母，数字，下划线）
      if (!value) {
        return callback(new Error('账户名不能为空！'))
      } else {
        if (uPattern.test(value) === false) {
          callback(new Error('6到16位（字母，数字，下划线）'))
        } else {
          callback()
        }
      }
    }
    var validatePass = (rule, value, callback) => {
      let pPattern = /^[a-zA-Z0-9]{6,16}$/ // 密码正则，6到16位（字母，数字，下划线）
      if (value === '') {
        callback(new Error('密码不能为空！'))
      } else {
        if (pPattern.test(value) === false) {
          callback(new Error('6到16位（字母，数字，下划线）'))
        } else {
          callback()
        }
      }
    }
    var validateRePass = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请再次输入密码'))
      } else if (value !== this.addForm.Password) {
        callback(new Error('两次输入密码不一致!'))
      } else {
        callback()
      }
    }
    return {
      backuping: false,
      selectTime: '',
      pickerOptions2: {
        shortcuts: [{
          text: '最近一周',
          onClick (picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
            picker.$emit('pick', [start, end])
          }
          // },
          //   {
          //   text: '最近一个月',
          //   onClick(picker) {
          //     const end = new Date();
          //     const start = new Date();
          //     start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
          //     picker.$emit('pick', [start, end]);
          //   }
          // }, {
          //   text: '最近三个月',
          //   onClick(picker) {
          //     const end = new Date();
          //     const start = new Date();
          //     start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
          //     picker.$emit('pick', [start, end]);
          //   }
        }]
      },
      searchFrom: {
        name: ''
      },
      tableData: [],
      pageIndex: 1,
      pageSize: 10,
      totalNum: 0,
      dialogFormVisible: false,
      detailEditType: 'detail', // 'edit'
      userDetail: {
        Name: ''
      },
      initAddForm: {
        UserID: '',
        Account: '',
        UserName: '',
        Sex: 0,
        Password: '',
        RePassword: ''
      },
      addForm: {},
      sexList: [
        {label: '未知', val: 0},
        {label: '男', val: 1},
        {label: '女', val: 2}
      ],
      rulesAdd: {
        UserName: [
          { required: true, message: '账户真实姓名', trigger: 'blur' }
        ],
        Account: [
          { validator: validateAccount, required: true, trigger: 'blur' }
        ],
        Password: [
          { validator: validatePass, required: true, trigger: 'blur' }
        ],
        RePassword: [
          { validator: validateRePass, required: true, trigger: 'blur' }
        ]
      },
      plantSelection: [],
      deletIds: []
    }
  },
  components: {},
  filters: {
    sexFilter (val) {
      let str
      let vals = val + ''
      switch (vals) {
        case '1':
          str = '男'
          break
        case '2':
          str = '女'
          break
        default:
          str = '未知'
      }
      return str
    }
  },
  created () {
    this.addForm = Object.assign({}, this.initAddForm)
    this.getBackupList()
  },
  mounted () {},
  methods: {
    getBackupList () {
      systemApi.getBackupList({
        PageIndex: this.pageIndex,
        pageSize: this.pageSize,
        timeRange: this.selectTime
      }).then((res) => {
        if (res.data.messageType === 0) {
          let result = res.data.result
          this.tableData = result.rows
          this.totalNum = result.Records
        } else {
          this.tableData = []
        }
      })
    },
    addBackupDialog () {
      this.detailEditType = 'add'
      this.dialogFormVisible = true
      this.addForm = Object.assign({}, this.initAddForm)
    },
    addBcakup () {
      this.backuping = true
      systemApi.dataBackup().then((res) => {
        console.log(res)
        if (res.data.messageType === 0) {
          this.$notify({
            title: '消息',
            message: ('备份成功!'),
            position: 'bottom-right',
            showClose: false,
            type: 'success'
          })
          this.backuping = false
          this.dialogFormVisible = false
          this.getBackupList()
        } else {
          this.$notify({
            title: '消息',
            message: ('备份成功!'),
            position: 'bottom-right',
            showClose: false,
            type: 'warning'
          })
          this.backuping = false
        }
      })
    },
    updateDetailSubmit (formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          let params = this.addForm
          systemApi.updateUser(params).then((res) => {
            if (res.data.MessageType === 0) {
              this.addForm = Object.assign({}, this.initAddForm)
              this.$notify({
                title: '消息',
                message: ('操作成功!'),
                position: 'bottom-right',
                showClose: false,
                type: 'success'
              })
              this.dialogFormVisible = false
            }
          })
        } else {
          return false
        }
      })
    },
    // 当前页
    pager (val) {
      this.pageIndex = val
      this.getBackupList()
    },
    download (row) {
      let url = process.env.DOMAIN + row.downloadUrl.replace(/"/g, '')
      window.location.href = url
      // this.dialogFormVisible = true
      // this.detailEditType = 'edit'
      // this.addForm = Object.assign({}, row)
      // this.addForm.RePassword = this.addForm.Password
    },
    deleteUser (row) {
      let tips = ''
      let params = {}
      if (row) {
        tips = `此操作将删除: ${row.UserName}, 是否继续?`
        params.UserID = row.UserID
      } else {
        return
      }
      this.$confirm(tips, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        systemApi.deleteUser(params).then((res) => {
          if (res.data.MessageType === 0) {
            this.$notify({
              title: '消息',
              message: ('删除成功！'),
              position: 'bottom-right',
              showClose: false,
              type: 'success'
            })
            this.getBackupList()
          }
        })
      }).catch((error) => {
        console.log(error)
      })
    }
  }
}
</script>
<style lang="less" scoped>
  .f-g-sd1{position:relative;float:left;width:95px;margin-right:-95px;}
  .f-g-mn1{float:right;width:100%;}
  .f-g-mn1c{margin-left:100px;}
  .detail-body{
    color: rgba(250, 250, 250, 0.9);
    &::after{
      content: '';
      display: block;
      visibility: hidden;
      height: 0;
      clear: both;
    }
  }
  .item-inline{
    width: 50%;
    float: left;
    margin-bottom: 20px;
    .item-name{
      display: inline-block;
    }
    .item-context{
      display: inline-block;
    }
  }

  .no-data{ text-align: center; font-size: 14px;
    .tips{
      padding:20px 0px; color: #666;
    }
  }
  .el-form-item__label{
    padding: 0 20px 0 0 !important;
  }
</style>
<style lang="less">
  /**
   * 修改样式   覆盖默认的饿了么全局样式
   */
  .el-form-item__label{
    padding: 0 20px 0 0 !important;
  }
  .el-picker-panel__sidebar{
    background-color: #000000;
  }
  .el-picker-panel__footer{
    background-color: #000000;
  }
  .el-date-table td.in-range div{
    background-color: #1a95b7;
  }
  /*.el-button.is-disabled.is-plain, .el-button.is-disabled.is-plain:hover, .el-button.is-disabled.is-plain:focus{*/
    /*background-color: #0089af;*/
  /*}*/
</style>
